package com.example.weiyujie

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.ComponentActivity
import android.graphics.Color


class MainActivity : ComponentActivity() {
    private lateinit var display: TextView
    private lateinit var historyDisplay: LinearLayout
    private var currentOperation = StringBuilder()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        display = findViewById(R.id.currentOperation)
        display.setTextColor(Color.RED)
        historyDisplay = findViewById(R.id.historyDisplay)

        historyDisplay.setOnClickListener {
            val intent = Intent(this, HistoryActivity::class.java)
            startActivity(intent)
        }

        val buttonIds = listOf(
            R.id.button0, R.id.button1, R.id.button2, R.id.button3,
            R.id.button4, R.id.button5, R.id.button6, R.id.button7,
            R.id.button8, R.id.button9
        )

        buttonIds.forEach { id ->
            findViewById<Button>(id).setOnClickListener { onNumberButtonClick(it as Button) }
        }

        val operatorButtonIds = listOf(
            R.id.buttonAdd, R.id.buttonSubtract, R.id.buttonMultiply, R.id.buttonDivide
        )

        operatorButtonIds.forEach { id ->
            findViewById<Button>(id).setOnClickListener { onOperatorButtonClick(it as Button) }
        }

        findViewById<Button>(R.id.buttonEqual).setOnClickListener { onEqualsButtonClick() }
        findViewById<Button>(R.id.buttonCancel).setOnClickListener { onCancelButtonClick() }
    }

    private fun onNumberButtonClick(button: Button) {
        currentOperation.append(button.text)
        display.text = currentOperation.toString()
    }

    private fun onOperatorButtonClick(button: Button) {
        currentOperation.append(" ${button.text} ")
        display.text = currentOperation.toString()
    }

    private fun onEqualsButtonClick() {
        val result = calculateResult(currentOperation.toString())
        val historyEntry = "${currentOperation.toString()} = $result"
        addHistory(historyEntry)
        saveHistoryToFile(historyEntry)
        display.text = result.toString()
        currentOperation.clear()
        currentOperation.append(result)
    }

    private fun onCancelButtonClick() {
        val currentText = display.text.toString()
        if (currentText.isNotEmpty()) {
            display.text = currentText.dropLast(1)
            currentOperation.setLength(currentOperation.length - 1)
        }
    }

    private fun calculateResult(operation: String): Double {
        val parts = operation.split(" ")
        if (parts.size < 3) return 0.0

        val num1 = parts[0].toDouble()
        val operator = parts[1]
        val num2 = parts[2].toDouble()

        return when (operator) {
            "+" -> num1 + num2
            "-" -> num1 - num2
            "*" -> num1 * num2
            "/" -> num1 / num2
            else -> 0.0
        }
    }

    private fun addHistory(historyEntry: String) {
        val historyTextView = TextView(this)
        historyTextView.text = historyEntry
        historyTextView.textSize = 18f
        historyTextView.setTextColor(Color.RED)
        historyTextView.gravity = android.view.Gravity.END
        historyDisplay.addView(historyTextView)
    }

    private fun saveHistoryToFile(historyEntry: String) {
        try {
            openFileOutput("history.txt", MODE_APPEND).use { fos ->
                fos.write((historyEntry + "\n").toByteArray())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}